//
//  UIImage+Extension.m
//  DoulinClient
//
//  Created by YLKJ on 2019/3/15.
//

#import "UIImage+Extension.h"

@implementation UIImage (Extension)

#pragma mark - --------------- WLCompress ----------------

- (NSData *)compressWithLengthLimit:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    NSLog(@"%@",[NSString stringWithFormat:@"原数据大小:%.4f MB",((double)data.length/1024.0f/1024.0f)]);
    //NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024);
    if (data.length < maxLength) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i){
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(self, compression);
        //NSLog(@"Compression = %.1f", compression);
        //NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
           break;
        }
    }
    //NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024);
    if (data.length < maxLength) return data;
    UIImage *resultImage = [UIImage imageWithData:data];
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        //NSLog(@"Ratio = %.1f", ratio);
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        //NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024);
    }
       //NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024);
    return data;
}

- (NSData *)compressQualityWithLengthLimit:(NSInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    while (data.length > maxLength && compression > 0) {
        compression -= 0.02;
        data = UIImageJPEGRepresentation(self, compression); // When compression less than a value, this code dose not work
    }
    return data;
}

- (NSData *)compressMidQualityWithLengthLimit:(NSInteger)maxLength{
    
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(self, compression);
    if (data.length < maxLength) {
        return data;
    }
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(self, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}

- (NSData *)compressBySizeWithLengthLimit:(NSUInteger)maxLength {
    UIImage *resultImage = self;
    NSData *data = UIImageJPEGRepresentation(resultImage, 1);
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        // Use image to draw (drawInRect:), image is larger but more compression time
        // Use result image to draw, image is smaller but less compression time
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, 1);
    }
    return data;
}

#pragma mark - -------------------------------
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGFloat imageW = 1;
    CGFloat imageH = 1;
    // 1.开启基于位图的图形上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageW, imageH), NO, 0.0);
    // 2.画一个color颜色的矩形框
    [color set];
    UIRectFill(CGRectMake(0, 0, imageW, imageH));
    // 3.拿到图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    // 4.关闭上下文
    UIGraphicsEndImageContext();
    return image;
}
- (UIImage *)ylScaleToSize:(CGSize)size {
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}
- (UIImage *)compressed {
    // Get image size
    CGSize size = self.size;
    // Create a graphics image context
    UIGraphicsBeginImageContext(size);
    // Tell the old image to draw in this new context, with the desired new size
    [self drawInRect:CGRectMake(0,0,size.width,size.height)];
    // Get the new image from the context
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Get new image data
    NSData * imageData = UIImageJPEGRepresentation(newImage,0.00001);
    // Return the new image.
    return [UIImage imageWithData:imageData];
}
- (UIImage *)zipImg {
    //进行图像尺寸的压缩
    CGSize imageSize = self.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    CGFloat limit = [UIScreen mainScreen].bounds.size.width / [UIScreen mainScreen].scale * 0.5;
    if (width > limit && height > limit) {//1.宽高大于1280(宽高比不按照2来算，按照1来算)
        if (width > height) {
            CGFloat scale = height / width;
            width = limit;
            height = width * scale;
        } else {
            CGFloat scale = width / height;
            height = limit;
            width = height * scale;
        }
    }else if(width > limit || height < limit){//2.宽大于1280高小于1280
        CGFloat scale = height / width;
        width = limit;
        height = width * scale;
    }else if(width < limit || height > limit){//3.宽小于1280高大于1280
        CGFloat scale = width / height;
        height = limit;
        width = height * scale;
    } else {//4.宽高都小于1280
        ;
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [self drawInRect:CGRectMake(0, 0, width, height)];
    UIImage * newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //进行图像的画面质量压缩
    NSData * data = UIImageJPEGRepresentation(newImg, 1.0);
    if (data.length > 100 * 1024) {
        if (data.length > 1024 * 1024) { //1M以及以上
            data = UIImageJPEGRepresentation(newImg, 0.7);
        }else if (data.length > 512 * 1024) { //0.5M-1M
            data = UIImageJPEGRepresentation(newImg, 0.8);
        }else if (data.length > 200 * 1024) { //0.25M-0.5M
            data = UIImageJPEGRepresentation(newImg, 0.9);
        }
    }
    return [UIImage imageWithData:data];
}

- (UIImage *)imageResizableWithName:(NSString *)imageName
{
    // 加载原有图片
    UIImage *norImage = [UIImage imageNamed:imageName];
    // 获取原有图片的宽高的一半
    CGFloat w = norImage.size.width * 0.5;
    CGFloat h = norImage.size.height * 0.5;
    // 生成可以拉伸指定位置的图片
    UIImage *newImage = [norImage resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w) resizingMode:UIImageResizingModeStretch];
    return newImage;
}

+ (UIImage *)imageStretchableImage:(NSString *)imageName WithLeftCapWidth:(NSInteger)width topCapHeight:(NSInteger)height{
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image stretchableImageWithLeftCapWidth:width topCapHeight:height];
    return image;
    
}
@end
